/**
 * Created by root on 15-1-5.
 */

define(['commonJS/module'], function(commonModule){

  /**
   * 指令，主导航栏
   */
  commonModule.directive('mainTopNav', ['$rootScope', '$state', 'commonModuleBaseUrl', 'LoginStatusService',
    function($rootScope, $state, commonModuleBaseUrl, LoginStatusService){

      return {
        restrict: 'E',
        templateUrl: commonModuleBaseUrl + 'tpls/mainTopNav.html',
        scope: {
          functionNavItems: '=functionNavItems'
        },
        link: function(scope, element, attr){

          var functionNavItemsSet = {}, lastItem = {};
          for( var i = 0; i < scope.functionNavItems.length; ++i ){
            functionNavItemsSet[ scope.functionNavItems[i]['name'] ] = scope.functionNavItems[i];
          }

          scope.personalInfo = LoginStatusService.get('personalInfo');
          scope.logoutUri = LoginStatusService.get('uri.logout');

          function highlightItem(state) {
            lastItem['active'] = false;

            var currItem = state.name.split('.')[0];

            if( currItem ) {
              functionNavItemsSet[ currItem ].active = true;
              lastItem = functionNavItemsSet[ currItem ];
            }
          }

          $rootScope.$on('$stateChangeSuccess', function(evt, toState, toParams){
            highlightItem(toState);
          });
        }
      };

    }]);

  commonModule.directive('commonNav', function(){

    return {
      controller: function(){

      }
    };
  });

  /**
   * 指令，模块使用的二级导航栏
   */
  commonModule.directive('moduleSecondNav', ['$rootScope', '$state', 'commonModuleBaseUrl', 'GoBackService', function($rootScope, $state, commonModuleBaseUrl, GoBackService){

    return {
      restrict: 'EA',
      templateUrl: commonModuleBaseUrl + 'tpls/module-second-nav.html',
      scope: {
        navItems: '=',
        compareLevel: '@',
        moduleName: '@'
      },
      link: function(scope){
        scope.compareLevel = parseInt(scope.compareLevel) || 2;

        /**
         * 提取状态中的前几级作为判断字段
         *
         * 示例：
         *  fetchValidStateOnUrl('abc.efg.hi', 2)
         *  >> abc.efg
         *
         * @param sourceUrl
         * @param stateNum
         * @returns {string}
         */
        function fetchValidStateOnUrl(sourceUrl, stateNum){
          var endPos = 0, counter = 0;

          for(var i = 0, length = sourceUrl.length; i < length; ++i ){
            if( sourceUrl[i] == '.' && ++counter && counter >= stateNum){
              endPos = i;
              break;
            }
          }

          if( counter == stateNum - 1 ){
            return sourceUrl;
          }else {
            return sourceUrl.substr(0, endPos);
          }

        }

        scope.navItemSet = {};
        //讲导航项目列表转化成k-v对的集合
        scope.navItems.forEach(function(currNavItem){
          scope.navItemSet[ fetchValidStateOnUrl(currNavItem['uiSref'], scope.compareLevel) ] = currNavItem;
        });

        var lastItem = {};
        //自动高亮当前项目的操作函数
        function highLight(stateName){
          lastItem['active'] = false;
          lastItem = scope.navItemSet[ fetchValidStateOnUrl(stateName, scope.compareLevel) ];
          lastItem['active'] = true;

          GoBackService.register('goBackToModule:' + scope.moduleName, lastItem);
        }

        highLight($state.current.name);

        //当路由改变时实现自动高亮
        $rootScope.$on('$stateChangeSuccess', function(event, toState){
          var toStateName = toState['name'];

          if( toStateName.indexOf(scope.moduleName) !== -1 ) {
            //如果不是处于`personal`的子状态则不进行操作
            highLight(toState['name']);
          }
        });
      }
    };
  }]);//End of --> moduleSecondNav

  /**
   *  指令，模块使用的三级导航栏
   */
  commonModule.directive('moduleThirdNav', ['$rootScope', '$state', 'commonModuleBaseUrl',
    function($rootScope, $state, commonModuleBaseUrl){

      return {
        restrict: 'EA',
        templateUrl: commonModuleBaseUrl + 'tpls/module-third-nav.html',
        scope: {
          navItems: '=',
          parentStateName: '@'
        },
        link: function(scope){
          scope.navItemSet = {};
          //讲导航项目列表转化成k-v对的集合
          scope.navItems.forEach(function(currNavItem){
            scope.navItemSet[ currNavItem['uiSref'] ] = currNavItem;
          });

          var lastItem = {};
          function highLight(stateName){
            lastItem['active'] = false;

            if( scope.navItemSet[ stateName ] ){
              lastItem = scope.navItemSet[ stateName ];
              lastItem['active'] = true;
            }
          }

          highLight($state.current.name);

          $rootScope.$on('$stateChangeSuccess', function(event, toState){
            if( toState.name.indexOf(scope.parentStateName) !== -1 ){
              highLight(toState.name);
            }
          });
        }
    };
  }]);//End of --> moduleThirdNav

  commonModule.directive('statusSwitch', ['commonModuleBaseUrl', function(commonModuleBaseUrl){

    return {
      restrict: 'EA',
      replace: true,
      templateUrl: commonModuleBaseUrl + 'tpls/status-switch.html',
      scope: {
        statusItems: '=',
        status: '='
      },
      link: function(scope){
        var currentItem  = null;

        for(var i = 0, length = scope.statusItems.length; i < length; ++i ){
          if( scope.statusItems[i]['value'] == scope.status ){
            currentItem = scope.statusItems[i];
            break;
          }
        }

        if( currentItem === null ){
          currentItem = scope.statusItems[0];
        }

        currentItem['active'] = true;
        scope.status = currentItem['value'];

        scope.toggle = function(selectedItem){
          currentItem['active'] = false;
          currentItem = selectedItem;
          currentItem['active'] = true;

          scope.status = currentItem['value'];
        }
      }
    };
  }]);//End of --> statusSwitch

  /**
   * 此指令用于按条件过滤讨论
   */
  commonModule.directive('filterOnCond', ['commonModuleBaseUrl',
    function(baseUrl){

      return {
        restrict: 'EA',
        replace: true,
        templateUrl: baseUrl + 'tpls/filter-on-cond.html',
        scope:{
          conditionObj: '=',
          conditions: '='
        },
        link: function(scope){
          scope.conditionObj = {};

          var lastItems = {};
          for( var item in scope.conditions ){
            lastItems[item] = scope.conditions[item][0];
            lastItems[item].selected = true;
          }

          scope.setSelected = function(currentCond, condName){
            lastItems[condName].selected = false;
            currentCond.selected = true;
            lastItems[condName] = currentCond;

            scope.conditionObj[condName] = currentCond.cond;
          };
        }
      };
    }]);//End of --> filterOnCond
});